const axios = require('axios');
const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV, // 使用当前环境
});
const rpcUtils = require('../utils/rpcUtils');
const orderUtils = require('../utils/orderUtils');
const timeUtils = require('../utils/timeUtils');
const EnvUtils = require('../utils/EnvUtils');
const db = cloud.database();
const _ = db.command; // 初始化数据库命令对象

// 技术通知URL
const techNotifyWebhookUrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=f8da0754-9364-4b5d-9451-027acf6ef994";

function buildMsContentForOrder(orderInfo) {
  let title = "**新订单通知**"
  const currentEnv = cloud.getWXContext().ENV
  if (currentEnv.includes('prod')) {
    title = "**新订单通知**"
  } else {
    title = "**【测试订单】新订单通知**"
  }

  let orderType = "-";
  orderType = orderUtils.getTypeDescByProductId(orderInfo.order_item.product_id);

  // 检查是否为代取快递且有急件
  let urgentFlag = false;
  let urgentTag = '';
  if (orderInfo.order_item.product_id === 'PPacakgePickUp' && Array.isArray(orderInfo.package_pickup_infos)) {
    urgentFlag = orderInfo.package_pickup_infos.some(item => item.pickup_size === '急件');
  }
  // selected_service_configs中有急件也算急件
  if (orderInfo.order_item.product_id === 'PPacakgePickUp' && Array.isArray(orderInfo.selected_service_configs)) {
    urgentFlag = urgentFlag || orderInfo.selected_service_configs.some(cfg => cfg.selectedService && cfg.selectedService.name === '急件');
  }
  if (urgentFlag) {
    urgentTag = '<font color="#fa1a16">【急件】</font>';
    orderType += urgentTag;
  }

  const timeStr = timeUtils.formatDateToYY_MM_DD_HH_MM_SS(orderInfo.create_ts);

  let content = `${title}\n` +
    `订单编号：<font color="warning">${orderInfo.order_id}</font>\n` +
    `订单类型：${orderType}\n` +
    `联系人：${orderInfo.address.name}\n` +
    `电话：${orderInfo.address.phone}\n` +
    `下单时间：${timeStr}\n`+
    `支付金额：${orderInfo.pay_amount}\n`;
  
  // 添加服务配置信息
  if (orderInfo.selected_service && Array.isArray(orderInfo.selected_service) && orderInfo.selected_service.length > 0) {
    const serviceItems = orderInfo.selected_service.map(item => 
      `${item.selectedService.name} x${item.quantity}`
    ).join('，');
    content += `服务配置：${serviceItems}\n`;
  }
  return content;
}

function buildPaotuiMsContentForOrder(orderInfo){
  let title = "**新订单通知**"
  const currentEnv = cloud.getWXContext().ENV
  if (currentEnv.includes('prod')) {
    title = "**新订单通知**"
  } else {
    title = "**【测试订单】新订单通知**"
  }

  let orderType = "-";
  orderType = orderUtils.getTypeDescByProductId(orderInfo.order_item.product_id);

  const timeStr = timeUtils.formatDateToYY_MM_DD_HH_MM_SS(orderInfo.create_ts);

  let content = `${title}\n` +
    `订单编号：<font color="warning">${orderInfo.order_id}</font>\n` +
    `订单类型：${orderType}\n` +
    `电话：${orderInfo.address.phone}\n` +
    `下单时间：${timeStr}\n`+
    `支付金额：${orderInfo.pay_amount}\n`;
  
  // 添加服务配置信息
  if (orderInfo.pao_tui_tasks && Array.isArray(orderInfo.pao_tui_tasks) && orderInfo.pao_tui_tasks.length > 0) {
    const serviceItems = orderInfo.pao_tui_tasks.map(item => 
      `${item.serviceName}`
    ).join('，');
    content += `跑腿具体服务名称：${serviceItems}\n`;
  }

  return content;
}

async function getNotifyUrl(orderDoc) {

  // if(!EnvUtils.isProdEnv()){
  //   return techNotifyWebhookUrl;
  // }
  
  const schoolCode = orderDoc.address?.schoolCode;
  if (!schoolCode) {
    return techNotifyWebhookUrl;
  }

  try {
    // 从配置表中获取学校对应的通知URL
    const config = await db.collection('config')
      .where({
        school_code: schoolCode,
        config_name: 'notifyWebhookConfig'
      })
      .get();

    if (config.data && config.data.length > 0) {
      const webhookUrl = config.data[0].content?.webhookUrl;
      if (webhookUrl) {
        return webhookUrl;
      }
    }
    
    return techNotifyWebhookUrl;
  } catch (error) {
    console.error('获取通知URL配置失败:', error);
    return techNotifyWebhookUrl;
  }
}

async function notifyOrderToStaff(request) {
  if (!request.orderId) {
    throw new Error('orderId is required');
  }

  let condition = {};
  condition.order_id = request.orderId;
  const ordersRes = await db.collection("order").where(condition).get();
  const orderDoc = ordersRes.data[0];

  let content;
  if(orderDoc.order_item.product_id === "PPaoTui") {
    content = buildPaotuiMsContentForOrder(orderDoc)
  }else{
    content = buildMsContentForOrder(orderDoc)
  }
  let data = {}
  data.msgtype = "markdown";
  data.markdown = {};
  data.markdown.content = content;
  let webhookUrl = await getNotifyUrl(orderDoc)
  const response = await axios.post(
    webhookUrl,
    data
  );
  return rpcUtils.genResp(rpcUtils.codeEnum.SUCCESS,"success",null);
}

async function notifyAbnormlOrderStautsToStaff(checkResult, orderInfo) {
  console.log("订单状态异常",JSON.stringify(orderInfo));
  let title = "**异常订单通知**"

  let orderType = "-";
  orderType = orderUtils.getTypeDescByProductId(orderInfo.order_item.product_id);
  // 检查是否为代取快递且有急件
  let urgentFlag = false;
  let urgentTag = '';
  if (orderInfo.order_item.product_id === 'PPacakgePickUp' && Array.isArray(orderInfo.package_pickup_infos)) {
    urgentFlag = orderInfo.package_pickup_infos.some(item => item.pickup_size === '急件');
  }
  if (urgentFlag) {
    urgentTag = '<font color="#fa8c16">【急件】</font>';
    orderType += urgentTag;
  }
  const timeStr = timeUtils.formatDateToYY_MM_DD_HH_MM_SS(orderInfo.create_ts);
  let content = `${title}\n` +
    `异常原因：<font color="warning">${checkResult.statusErrorMsg}</font>\n` +
    `订单编号：<font color="warning">${orderInfo.order_id}</font>\n` +
    `订单类型：${orderType}\n` +
    `联系人：${orderInfo.address.name}\n` +
    `电话：${orderInfo.address.phone}\n` +
    `下单时间：${timeStr}\n`+
    `支付金额：${orderInfo.pay_amount}\n`;
  
  // 添加服务配置信息
  if (orderInfo.selected_service && Array.isArray(orderInfo.selected_service) && orderInfo.selected_service.length > 0) {
    const serviceItems = orderInfo.selected_service.map(item => 
      `${item.selectedService.name} x${item.quantity}`
    ).join('，');
    content += `服务配置：${serviceItems}\n`;
  }
  
  let data = {}
  data.msgtype = "markdown";
  data.markdown = {};
  data.markdown.content = content;
  const response = await axios.post(
    techNotifyWebhookUrl,
    data
  );
}

module.exports = {
  notifyOrderToStaff: notifyOrderToStaff,
  notifyAbnormlOrderStautsToStaff: notifyAbnormlOrderStautsToStaff
};